package org.taie.simplequeue;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.util.List;

/**
 * User: AbelZ
 * Date: 2011-1-26
 * Time: 20:28:37
 */
public class Journal {

    private static final Log logger = LogFactory.getLog(Journal.class);

    private String queuePath;
    private boolean sync;

    private byte[] buffer = new byte[16];
    private ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);

    private FileChannel writer;


    public Journal(String queuePath, boolean sync) {
        this.queuePath = queuePath;
        this.sync = sync;

        byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
    }


    private FileChannel open(File file) throws FileNotFoundException {
        return new FileOutputStream(file).getChannel();
    }

    public void open() throws FileNotFoundException {
        open(new File(queuePath));
    }




    private byte[] readBlock(FileChannel in) throws IOException {
        int size = readInt(in);
        byte[] data = new byte[size];
        ByteBuffer dataBuffer = ByteBuffer.wrap(data);
        int x = 0;
        do {
            x = in.read(dataBuffer);
        } while (dataBuffer.position() < dataBuffer.limit() && x >= 0);
        if (x < 0) {
            // we never expect EOF when reading a block.
            throw new IOException("Unexpected EOF");
        }

        return data;
    }

    private int readInt(FileChannel in) throws IOException {
        byteBuffer.rewind();
        byteBuffer.limit(4);
        int x = 0;

        do {
            x = in.read(byteBuffer);
        } while (byteBuffer.position() < byteBuffer.limit() && x >= 0);

        if (x < 0) {
            // we never expect EOF when reading an int.
            throw new IOException("Unexpected EOF");
        }

        byteBuffer.rewind();
        return byteBuffer.getInt();
    }


    private int write(List<Message> msgLst, boolean allowSync) throws IOException {
        byteBuffer.clear();

        for (Message msg : msgLst) {
//            byteBuffer.put(1);
        }

        byteBuffer.flip();
        while (byteBuffer.position() < byteBuffer.limit()) {
            writer.write(byteBuffer);
        }
        return byteBuffer.limit();
    }

}
